<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="药品名称">
          <el-input v-model="searchForm.drugName" placeholder="请输入药品名称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="药品编码">
          <el-input v-model="searchForm.drugCode" placeholder="请输入药品编码" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="效期状态">
          <el-select v-model="searchForm.expiryStatus" placeholder="请选择效期状态" clearable>
            <el-option label="即将过期" value="nearExpiry" />
            <el-option label="已过期" value="expired" />
            <el-option label="全部" value="all" />
          </el-select>
        </el-form-item>
        <el-form-item label="天数">
          <el-input-number 
            v-model="searchForm.expiryDays" 
            :min="1" 
            :max="365" 
            placeholder="过期/即将过期天数"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>药品效期预警</h3>
          <div>
            <el-button 
              type="primary" 
              @click="exportExpiringList" 
              v-permission="'drug_inventory:read'"
            >
              导出列表
            </el-button>
            <el-button 
              type="danger" 
              @click="batchDiscard" 
              :disabled="selection.length === 0"
              v-permission="'drug_inventory:update'"
            >
              批量报废
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="expiringList"
        border
        style="width: 100%"
        row-key="id"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="drugInfo.drugCode" label="药品编码" min-width="120" />
        <el-table-column prop="drugInfo.name" label="药品名称" min-width="150" />
        <el-table-column prop="drugInfo.specification" label="规格" min-width="120" />
        <el-table-column prop="batchNumber" label="批次号" min-width="120" />
        <el-table-column prop="quantity" label="库存数量" min-width="100">
          <template #default="scope">
            {{ scope.row.quantity }} {{ scope.row.unit || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="有效期至" min-width="120" sortable="custom">
          <template #default="scope">
            <span :class="getExpiryClass(scope.row)">
              {{ formatDate(scope.row.expirationDate) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remainingDays" label="剩余天数" min-width="100" sortable="custom">
          <template #default="scope">
            <el-tag :type="getExpiryTagType(scope.row.remainingDays)">
              {{ getRemainingDaysText(scope.row.remainingDays) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="drugInfo.manufacturer" label="生产厂家" min-width="150" show-overflow-tooltip />
        <el-table-column prop="receiveDate" label="采购日期" min-width="120">
          <template #default="scope">
            {{ scope.row.receiveDate ? new Date(scope.row.receiveDate).toLocaleDateString() : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleViewDetail(scope.row)"
              v-permission="'drug_inventory:read'"
            >
              详情
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDiscard(scope.row)"
              v-permission="'drug_inventory:update'"
            >
              报废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="page"
          v-model:page-size="limit"
          @size-change="fetchExpiringDrugs"
          @current-change="fetchExpiringDrugs"
        />
      </div>
    </el-card>

    <!-- 报废对话框 -->
    <el-dialog
      title="药品报废"
      v-model="discardDialog.visible"
      width="500px"
    >
      <el-form :model="discardDialog.form" label-width="120px" ref="discardFormRef">
        <el-form-item label="药品名称">
          <el-input v-model="discardDialog.form.drugName" disabled />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="discardDialog.form.batchNumber" disabled />
        </el-form-item>
        <el-form-item label="有效期至">
          <el-input v-model="discardDialog.form.expiryDate" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="discardDialog.form.currentQuantity" disabled>
            <template #append>{{ discardDialog.form.unit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="报废数量" prop="discardQuantity">
          <el-input-number 
            v-model="discardDialog.form.discardQuantity" 
            :min="1" 
            :max="discardDialog.form.currentQuantity"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报废原因" prop="reason">
          <el-select v-model="discardDialog.form.reason" placeholder="请选择报废原因" style="width: 100%">
            <el-option label="过期" value="expired" />
            <el-option label="质量问题" value="quality" />
            <el-option label="包装破损" value="damaged" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="discardDialog.form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="discardDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="confirmDiscard" :loading="discardDialog.loading">
            确认报废
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量报废对话框 -->
    <el-dialog
      title="批量药品报废"
      v-model="batchDiscardDialog.visible"
      width="500px"
    >
      <el-form :model="batchDiscardDialog.form" label-width="120px" ref="batchDiscardFormRef">
        <el-form-item label="选中药品">
          <div class="selected-drugs">
            已选择 <span class="drug-count">{{ selection.length }}</span> 种药品
          </div>
        </el-form-item>
        <el-form-item label="报废原因" prop="reason">
          <el-select v-model="batchDiscardDialog.form.reason" placeholder="请选择报废原因" style="width: 100%">
            <el-option label="过期" value="expired" />
            <el-option label="质量问题" value="quality" />
            <el-option label="包装破损" value="damaged" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="batchDiscardDialog.form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDiscardDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="confirmBatchDiscard" :loading="batchDiscardDialog.loading">
            确认批量报废
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { drugInventoryAPI } from '@/utils/api'

const router = useRouter()

// 数据列表
const expiringList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(20)
const sortBy = ref('remainingDays')
const order = ref('asc')
const selection = ref([])

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  drugName: '',
  drugCode: '',
  expiryStatus: 'all',
  expiryDays: 30
})

// 报废对话框
const discardDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: '',
    drugName: '',
    batchNumber: '',
    expiryDate: '',
    currentQuantity: 0,
    discardQuantity: 0,
    unit: '',
    reason: 'expired',
    remark: ''
  }
})

// 批量报废对话框
const batchDiscardDialog = reactive({
  visible: false,
  loading: false,
  form: {
    reason: 'expired',
    remark: ''
  }
})

// 获取即将过期药品列表
const fetchExpiringDrugs = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      limit: limit.value,
      sortBy: sortBy.value,
      order: order.value,
      expiryDays: searchForm.expiryDays,
      expiryStatus: searchForm.expiryStatus,
      drugName: searchForm.drugName,
      drugCode: searchForm.drugCode
    }
    
    const res = await drugInventoryAPI.getExpiringDrugs(params)
    console.log('API响应:', res)
    
    if (res.success) {
      // 确保数据格式正确
      expiringList.value = res.data.inventory || []
      
      // 处理日期格式
      expiringList.value = expiringList.value.map(item => {
        // 确保expirationDate是可用于显示的格式
        if (item.expirationDate) {
          if (typeof item.expirationDate === 'string') {
            // 如果是ISO格式的字符串
            if (item.expirationDate.includes('T')) {
              item.expirationDate = new Date(item.expirationDate).toISOString().split('T')[0]
            }
            // 如果是简单的YYYY-MM-DD格式，保持不变
          } else {
            // 如果是Date对象，转换为YYYY-MM-DD格式
            item.expirationDate = new Date(item.expirationDate).toISOString().split('T')[0]
          }
        }
        
        // 如果后端没有提供remainingDays，在前端计算
        if (item.remainingDays === undefined && item.expirationDate) {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          const expiry = new Date(item.expirationDate)
          expiry.setHours(0, 0, 0, 0)
          const diffTime = expiry - today
          item.remainingDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        }
        
        return item
      })
      
      total.value = res.data.total || 0
      
      // 如果没有数据，显示提示
      if (expiringList.value.length === 0) {
        ElMessage.info('没有找到符合条件的即将过期药品')
      }
    } else {
      ElMessage.error(res.message || '获取即将过期药品列表失败')
    }
  } catch (error) {
    console.error('获取即将过期药品列表失败', error)
    ElMessage.error('获取即将过期药品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchExpiringDrugs()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  page.value = 1
  fetchExpiringDrugs()
}

// 排序变化
const handleSortChange = (column) => {
  if (column.prop) {
    sortBy.value = column.prop
    order.value = column.order === 'ascending' ? 'asc' : 'desc'
    fetchExpiringDrugs()
  }
}

// 表格选择变化
const handleSelectionChange = (val) => {
  selection.value = val
}

// 查看库存详情
const handleViewDetail = (row) => {
  router.push(`/drugs/inventory/detail/${row.id}`)
}

// 格式化日期显示
const formatDate = (dateStr) => {
  if (!dateStr) return '未设置'
  
  try {
    // 尝试创建日期对象
    const date = new Date(dateStr)
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return dateStr // 如果不是有效日期，直接返回原字符串
    }
    
    // 格式化为本地日期格式
    return date.toLocaleDateString()
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateStr
  }
}

// 获取剩余天数的文本显示
const getRemainingDaysText = (days) => {
  if (days < 0) {
    return `已过期${Math.abs(days)}天`
  } else if (days === 0) {
    return '今日过期'
  } else {
    return `剩余${days}天`
  }
}

// 获取有效期的CSS类
const getExpiryClass = (row) => {
  if (row.remainingDays < 0) {
    return 'expired-text'
  } else if (row.remainingDays <= 30) {
    return 'warning-text'
  }
  return ''
}

// 获取有效期标签类型
const getExpiryTagType = (days) => {
  if (days < 0) {
    return 'danger'
  } else if (days <= 7) {
    return 'danger'
  } else if (days <= 30) {
    return 'warning'
  } else if (days <= 90) {
    return 'info'
  }
  return 'success'
}

// 导出列表
const exportExpiringList = () => {
  ElMessage.info('导出功能开发中...')
  // TODO: 实现导出功能
}

// 报废单个药品
const handleDiscard = (row) => {
  discardDialog.form.id = row.id
  discardDialog.form.drugName = row.drugInfo?.name || ''
  discardDialog.form.batchNumber = row.batchNumber
  discardDialog.form.expiryDate = formatDate(row.expirationDate)
  discardDialog.form.currentQuantity = row.quantity
  discardDialog.form.discardQuantity = row.quantity
  discardDialog.form.unit = row.unit || ''
  discardDialog.form.reason = 'expired'
  discardDialog.form.remark = row.remainingDays < 0 ? '药品已过期' : '药品即将过期'
  discardDialog.visible = true
}

// 确认报废
const confirmDiscard = async () => {
  if (!discardDialog.form.reason) {
    ElMessage.warning('请选择报废原因')
    return
  }

  discardDialog.loading = true
  try {
    const res = await drugInventoryAPI.updateInventory(discardDialog.form.id, {
      adjustQuantity: -discardDialog.form.discardQuantity,
      reason: 'discard',
      discardReason: discardDialog.form.reason,
      remark: discardDialog.form.remark
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('药品报废成功')
      discardDialog.visible = false
      fetchExpiringDrugs()
    } else {
      ElMessage.error(res.data.message || '药品报废失败')
    }
  } catch (error) {
    console.error('药品报废失败', error)
    ElMessage.error('药品报废失败')
  } finally {
    discardDialog.loading = false
  }
}

// 批量报废
const batchDiscard = () => {
  if (selection.value.length === 0) {
    ElMessage.warning('请至少选择一种药品')
    return
  }
  
  batchDiscardDialog.form.reason = 'expired'
  batchDiscardDialog.form.remark = '批量报废过期/即将过期药品'
  batchDiscardDialog.visible = true
}

// 确认批量报废
const confirmBatchDiscard = async () => {
  if (!batchDiscardDialog.form.reason) {
    ElMessage.warning('请选择报废原因')
    return
  }

  batchDiscardDialog.loading = true
  try {
    // 创建批量报废请求
    const requests = selection.value.map(item => {
      return drugInventoryAPI.updateInventory(item.id, {
        adjustQuantity: -item.quantity,
        reason: 'discard',
        discardReason: batchDiscardDialog.form.reason,
        remark: batchDiscardDialog.form.remark
      })
    })
    
    // 同时发送所有请求
    const results = await Promise.all(requests)
    
    // 检查结果
    const failures = results.filter(res => !res.success).length
    
    if (failures === 0) {
      ElMessage.success(`${selection.value.length}种药品批量报废成功`)
      batchDiscardDialog.visible = false
      fetchExpiringDrugs()
    } else {
      ElMessage.warning(`${selection.value.length - failures}种药品报废成功，${failures}种药品报废失败`)
      batchDiscardDialog.visible = false
      fetchExpiringDrugs()
    }
  } catch (error) {
    console.error('批量报废失败', error)
    ElMessage.error('批量报废失败')
  } finally {
    batchDiscardDialog.loading = false
  }
}

// 生命周期钩子
onMounted(() => {
  fetchExpiringDrugs()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.warning-text {
  color: #E6A23C;
  font-weight: bold;
}
.expired-text {
  color: #F56C6C;
  font-weight: bold;
}
.selected-drugs {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.drug-count {
  font-weight: bold;
  color: #F56C6C;
}
</style>